package com.lvxh.exp.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.lvxh.exp.expuser.dao.holder.Expuser;
import com.lvxh.exp.filter.global.Constant;
import com.lvxh.exp.filter.global.ExpContext;
import com.lvxh.exp.filter.global.GlobalObject;

public class ExpFilter implements Filter, Constant
{

    public void destroy()
    {

    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rsp = (HttpServletResponse) response;
        GlobalObject bean = ExpContext.getInstance().getCtx().getBean("globalObject", GlobalObject.class);
        String url = req.getRequestURI();
        if (bean.getNoAuthUrlList().contains(url))
        {

            chain.doFilter(request, response);
        }
        else
        {
            Expuser user = (Expuser) req.getSession().getAttribute(
                    AUTH_EXP_USER);
            if (user != null)
            {
                chain.doFilter(request, response);
            }
            else
            {
                req.getSession().invalidate();
                rsp.sendRedirect(req.getContextPath() + LOGIN_ACTION);
                return;
            }
        }

    }

    public void init(FilterConfig config) throws ServletException
    {

        System.out.println("....................start init filter!");
        ApplicationContext ctx = WebApplicationContextUtils
                .getWebApplicationContext(config.getServletContext());
        ExpContext.getInstance().setCtx(ctx);
        System.out.println("....................end init filter!");

    }
}